package study.eggs.springcloud.gateway.support.utils;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.web.server.ServerWebExchange;

import java.net.URI;
import java.util.Map;
import java.util.Set;

@Slf4j
public final class ExchangeUtils {

    private ExchangeUtils() {
    }

    /**
     * 获取路由
     */
    public static Route getRoute(ServerWebExchange exchange) {
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        return route;
    }

    /**
     * 获取原始Path
     */
    public static String getPath(ServerWebExchange exchange) {
        URI uri = exchange.getRequest().getURI();
        uri.getRawPath();
        uri.getPath();
        log.info("{}", getGatewayOriginalRequestURI(exchange).getPath());
        return uri.getPath();
    }

    /**
     * 获取原始Path
     */
    public static String getOriginalPath(ServerWebExchange exchange) {
        return getGatewayOriginalRequestURI(exchange).getPath();
    }

    /**
     * 获取网关请求URI
     */
    public static URI getGatewayRequestURI(ServerWebExchange exchange) {
        URI uri = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR);
        return uri;
    }


    /**
     * 获取原始路由url
     */
    public static URI getGatewayOriginalRequestURI(ServerWebExchange exchange) {
        Set<URI> uriSet = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR);
        if (CollectionUtil.isEmpty(uriSet)) {
            return URI.create("/");
        }
        return CollectionUtil.getFirst(uriSet);
    }

    /**
     * 放置属性
     */
    public static <T> void putAttr(ServerWebExchange exchange, String key, T value) {
        Map<String, Object> attrs = exchange.getAttributes();
        attrs.put(key, value);
    }

    /**
     * 获取属性
     */
    public static <T> T getAttr(ServerWebExchange exchange, String key) {
        return exchange.getAttribute(key);
    }
}
